import 'dart:async';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await initService();
  runApp(MyApp());
}

Future<void> initService() async {
  final service = FlutterBackgroundService();

  const AndroidNotificationChannel channel = AndroidNotificationChannel(
    'foreground', // 与下方一致
    '前台服务',
    description: '保持任务运行',
    importance: Importance.high,
  );

  final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
  await flutterLocalNotificationsPlugin
      .resolvePlatformSpecificImplementation<
        AndroidFlutterLocalNotificationsPlugin
      >()
      ?.createNotificationChannel(channel);

  await service.configure(
    androidConfiguration: AndroidConfiguration(
      onStart: onStart,
      autoStart: true,
      isForegroundMode: true,
      notificationChannelId: 'foreground',
      initialNotificationTitle: '服务运行中',
      initialNotificationContent: '点击返回应用',
      foregroundServiceNotificationId: 888,
    ),
    iosConfiguration: IosConfiguration(
      autoStart: true,
      onForeground: onStart,
      onBackground: (s) => true,
    ),
  );
}

@pragma('vm:entry-point')
void onStart(ServiceInstance service) {
  DartPluginRegistrant.ensureInitialized();

  if (service is AndroidServiceInstance) {
    // 必须 5 秒内调用
    service.setForegroundNotificationInfo(title: '服务运行中', content: '点击返回应用');
    service.on('setAsForeground').listen((event) {
      service.setAsForegroundService();
    });

    service.on('setAsBackground').listen((event) {
      service.setAsBackgroundService();
    });
  }

  service.on('stopService').listen((event) {
    service.stopSelf();
  });

  Timer.periodic(const Duration(seconds: 10), (timer) async {
    if (service is AndroidServiceInstance) {
      service.setForegroundNotificationInfo(
        title: "后台服务",
        content: "更新时间: ${DateTime.now()}",
      );
    }

    print('后台任务运行中: ${DateTime.now()}');
  });
}

@pragma('vm:entry-point')
void onIosForeground(ServiceInstance service) {
  // iOS 前台逻辑
}

@pragma('vm:entry-point')
FutureOr<bool> onIosBackground(ServiceInstance service) {
  // iOS 后台逻辑
  return true;
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('后台服务示例')),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: () {
                  FlutterBackgroundService().invoke('setAsForeground');
                },
                child: Text('设置为前台服务'),
              ),
              ElevatedButton(
                onPressed: () {
                  FlutterBackgroundService().invoke('setAsBackground');
                },
                child: Text('设置为后台服务'),
              ),
              ElevatedButton(
                onPressed: () {
                  FlutterBackgroundService().invoke('stopService');
                },
                child: Text('停止服务'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
